package generate

// Define a code generation template
const (
	serviceTemplate = `package service

type {{.ModelName}}Service struct {
}

func (s *{{.ModelName}}Service) {{.ModelName}}AddOne(d *dto.{{.ModelName}}AddDTO) error {
	var err error
	m := &model.{{.ModelName}}Model{}
	{{range getColumns .}}{{if isPrimaryKey .Key}}{{else}}
	if d.{{.ModelName}} != nil {
		err = m.{{.ModelName}}.Scan(*d.{{.ModelName}})
		if err != nil {
			return err
		}
	}{{end}}{{end}}

	// 插入
	err = m.AddOne()
	if err != nil {
		return err
	}
	return nil
}

func (s *{{.ModelName}}Service) {{.ModelName}}DelById(i int) error {
	if i <= 0 {
		return utils.ParamError
	}
	m := &model.{{.ModelName}}Model{}
	err := m.DeleteById(i)
	if err != nil {
		return err
	}
	return nil
}

func (s *{{.ModelName}}Service) {{.ModelName}}UpdateById(d *dto.{{.ModelName}}UpdateDTO) error {
	{{range getColumns .}}{{if isPrimaryKey .Key}}
	if d.{{.ModelName}} == nil {
		return utils.ParamError
	}{{end}}{{end}}
	var err error
	m := &model.{{.ModelName}}Model{}

	{{range getColumns .}}
	if d.{{.ModelName}} != nil {
		err = m.{{.ModelName}}.Scan(*d.{{.ModelName}})
		if err != nil {
			return err
		}
	}{{end}}

	err = m.UpdateById()
	if err != nil {
		return err
	}

	return nil
}

func (s *{{.ModelName}}Service) {{.ModelName}}PageList(param *dto.{{.ModelName}}SelectDTO) (interface{}, error) {
	m := &model.{{.ModelName}}Model{}
	list, err := m.PageList(param)
	if err != nil {
		return nil, err
	}
	res := &vo.PageVo{}
	res.To(list)

	switch list.List.(type) {
	case []*model.{{.ModelName}}Model:
		tempList := list.List.([]*model.{{.ModelName}}Model)
		result := make([]*vo.{{.ModelName}}Vo, 0, len(tempList))
		res.Size = len(tempList)
		for _, activity := range tempList {
			temp := &vo.{{.ModelName}}Vo{}
			temp.To(activity)
			result = append(result, temp)
		}
		res.List = result
	default:
		return nil, errors.New("{{.ModelName}}PageList.类型转换[]*model.{{.ModelName}}Model失败")
	}
	return res, nil
}
`
)
